/**
 * @file app_sntp.c
 * @author Ai-Thinker Seahi
 * @brief
 * @version 0.1
 * @date 2021-09-25
 *
 * @copyright Copyright (c) 2021
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "app_sntp.h"
#include "app_oled.h"
static char* TAG = "SNTTP";

/**
 * @brief 获取SNTP 时间
 *
 */
static struct tm get_sntp_time()
{
    struct tm timeinfo;
    time_t now = 1631758497;
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "ntp1.aliyun.com");
    sntp_init();
    setenv("TZ", "CST-8", 1);
    tzset();
    while ((now < 1631758498)) {
        vTaskDelay(20 / portTICK_RATE_MS);
        time(&now);
    }
    time(&now);
    SNTP_SET_SYSTEM_TIME(now);
    localtime_r(&now, &timeinfo);
    sntp_stop();
    return timeinfo;
}
/**
 * @brief 获取网络事件任务
 *
 * @param arg
 */
void get_sntp_task(void* arg)
{
    char strftime_buf[64];
    struct tm timeinfo;
    timeinfo = get_sntp_time();
    for (;;) {
        memset(strftime_buf, 0, 64);
        timeinfo = get_sntp_time();
        sprintf(strftime_buf, "%d-%02d-%02d w: %d", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday, timeinfo.tm_wday);
        ESP_LOGW(TAG, "%s", strftime_buf);
        if (OLED_INIT_OK)
            oled_display_str_time(0, 2, timeinfo);
        vTaskDelay(1000 / portTICK_RATE_MS);
    }
}
